<?php

namespace LaBaiCai;
/**
 * Created by : Aaron Chang
 * Date : 2023-08-03
 * @docUrl :  https://developer.danghongyun.com/rest_api_live.html
 */
class DangHong
{
    protected $accessKey = '';
    protected $accessSecret = '';
    protected $apiUrl = 'http://api.danghongyun.com/rest?';

    public function __construct(array $config)
    {
        foreach ($config as $k => $v) {
            $this->$k = $v;
        }
    }

    /****
     * 拼接URL
     * @param array $dataArr
     * @return bool|string
     */
    public function mkUrl(array $dataArr)
    {
        $url = '';
        foreach ($dataArr as $key => $value) {
            $url .= $key . '=' . $value . '&';
        }
        return substr($url, 0, strlen($url) - 1);
    }

    /***
     * 生成签名
     * @param array $arr
     * @param $accessKey
     * @param $accessSecret
     * @return string
     */
    public function mkSig(array $arr, $accessKey, $accessSecret)
    {
        ksort($arr);
        $request = $accessSecret;
        foreach ($arr as $key => $value) {
            $request .= $key . '=' . $value;
        }
        return hash_hmac('sha256', $request, $accessSecret);
    }

    /**
     * 删除直播频道
     * @param $liveIds array
     * @return false|void
     */
    public function liveDelete(array $liveIds)
    {
        if (!empty($liveId)) {
            return $this->sendPostRequest('liveDelete', ['ids' => $liveId]);
        } else {
            return false;
        }
    }

    /**
     * 开始直播
     * @param $liveId
     * @return false|void
     */
    public function liveStartChannel($liveId)
    {
        if (!empty($liveId)) {
            return $this->sendPostRequest('liveStartChannel', ['id' => $liveId]);
        } else {
            return false;
        }
    }

    /**
     * 停止直播
     * @param $liveId
     * @return void|bool
     */
    public function liveStopChannel($liveId)
    {
        if (!empty($liveId)) {
            return $this->sendPostRequest('liveStopChannel', ['id' => $liveId]);
        } else {
            return false;
        }
    }

    /**
     * 设置直播频道状态回调地址
     * @param $value
     * @return void|bool
     */
    public function setLiveCallback($value)
    {
        if (!empty($value)) {
            return $this->sendPostRequest('setLiveCallback', ['value' => $value]);
        } else {
            return false;
        }
    }

    /**
     * 根据ID查询频道信息
     * @param $liveId string
     * @return array|false
     */
    public function liveGetChannelById(string $liveId)
    {
        if (!empty($value)) {
            return $this->sendGetRequest('liveGetChannelById', ['id' => $liveId]);
        } else {
            return false;
        }
    }

    /**
     * 开始录制
     * @param $liveId
     * @param $outputGroupId
     * @return array|false
     */
    public function liveStartChannelRecord($liveId, $outputGroupId)
    {
        if (!empty($value)) {
            return $this->sendPostRequest('liveStartChannelRecord', ['channelId' => $liveId, 'outputGroupId' => $outputGroupId]);
        } else {
            return false;
        }
    }

    /**
     * 结束录制
     * @param $liveId
     * @param $outputGroupId
     * @return array|false
     */
    public function liveStopChannelRecord($liveId, $outputGroupId)
    {
        if (!empty($value)) {
            return $this->sendPostRequest('liveStopChannelRecord', ['channelId' => $liveId, 'outputGroupId' => $outputGroupId]);
        } else {
            return false;
        }
    }

    /**
     * 向当虹云发送POST请示
     * @param $action string 动作 如：liveChannelTypeCreate
     * @param $data   array 除了必要的参数外， 其它附加参数， 如： ['id'=>$channelId]
     * @return mixed 当虹云响应内容
     * @throws GuzzleException
     */
    protected function sendPostRequest(string $action, array $data = [])
    {
        return $this->sendRequest("POST", $action, $data);
    }

    /**
     * 向当虹云发送GET请示
     * @param $action  string  如：liveChannelTypeCreate
     * @param $data    array 除了必要的参数外， 其它附加参数， 如： ['id'=>$channelId]
     * @return mixed 当虹云响应内容
     * @throws GuzzleException
     */

    protected function sendGetRequest(string $action, array $data = [])
    {
        return $this->sendRequest('GET', $action, $data);
    }

    /**
     * 发送当晓云请求
     * @param $method string GET/POST
     * @param $action string 动作 如：liveChannelTypeCreate
     * @param $data array  除了必要的参数外， 其它附加参数， 如： ['id'=>$channelId]
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function sendRequest(string $method, string $action, array $data = [])
    {
        try {
            if (empty($this->accessKey) || empty($this->accessSecret)) {
                return ['code' => 400, 'message' => '未配置[accessKey]和[accessSecret]'];
            }

            $paramBody = [];
            $paramHeaderRecord = array(
                'accessKey' => $this->accessKey,
                'action' => $action,
                'version' => '2.0',
                'timestamp' => time(),
            );
            foreach ($data as $k => $v) {
                if ($k == 'body') {
                    $paramBody['body'] = $v;
                    continue;
                }
                $paramHeaderRecord[$k] = $v;
            }

            $signSha = $this->mkSig($paramHeaderRecord, $this->accessKey, $this->accessSecret);
            $paramHeaderRecord["signature"] = $signSha;
            $api = $this->apiUrl;

            $client = new \GuzzleHttp\Client();
            $url = $api . $this->mkUrl($paramHeaderRecord);
            $response = $client->request($method, $url, $paramBody);
            $response = json_decode($response->getBody()->getContents(), true);
            return $response;
        } catch (\Exception $exception) {
            return ['code' => 400, 'message' => $exception->getMessage()];
        }
    }
}